package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/go-resty/resty/v2"
	"net/http"
	"os"
	"strings"
)

const xtoken = "CC3CA5C5LuhYVeaEltkj9_c11dec198a78e39bbb9e7c50b3563ec8"
const XToken = "xtoken"

func main() {
	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Println("请输入要调用的接口编号（1-重颁发初始化，2-追加域名额度购买初始化，3-查询证书列表，q-退出）：")
		input, _ := reader.ReadString('\n')
		input = strings.TrimSpace(input)
		switch input {
		case "1":
			reissueInit("2c463920eabb47f09854b5c61c0cdda3")
		case "2":
			appendDomainQuotaInit(844)
		case "3":
			queryPage4Service()
		case "q", "Q":
			fmt.Println("退出程序")
			return
		default:
			fmt.Println("输入无效,请重新输入")
		}
	}
}

func testResty() {
	client := resty.New()
	resp, err := client.R().SetCookie(&http.Cookie{Name: XToken, Value: xtoken}).Get("https://test-ssl.xinnet.com/api/cert/order/appendDomainQuotaInit/844")
	if err != nil {
		fmt.Println(err)
		return
	}
	prettyStr(resp.Body())
}

// 追加域名额度购买初始化
func appendDomainQuotaInit(id int64) {
	url := fmt.Sprintf("https://test-ssl.xinnet.com/api/cert/order/appendDomainQuotaInit/%d", id)
	client := resty.New()
	resp, err := client.R().SetCookie(&http.Cookie{Name: XToken, Value: xtoken}).Get(url)
	if err != nil {
		fmt.Println(err)
		return
	}
	prettyStr(resp.Body())
}

// 重签发证书初始化
func reissueInit(serviceCode string) {
	url := fmt.Sprintf("https://test-ssl.xinnet.com/api/cert/order/reissueInit/%s", serviceCode)
	client := resty.New()
	resp, err := client.R().SetCookie(&http.Cookie{Name: XToken, Value: xtoken}).Get(url)
	if err != nil {
		fmt.Println(err)
		return
	}
	prettyStr(resp.Body())
}

func queryPage4Service() {
	url := "https://test-ssl.xinnet.com/api/cert/order/query/1/10"
	client := resty.New()
	params := map[string]string{
		"serviceCode": "c556d0fe38ab41e8ae1c40142a362b4d",
	}
	resp, err := client.
		R().
		SetHeader("Content-Type", "application/json").
		SetCookie(&http.Cookie{Name: XToken, Value: xtoken}).
		SetBody(params).
		Post(url)
	if err != nil {
		fmt.Println(err)
		return
	}
	prettyStr(resp.Body())
}

func prettyStr(data []byte) {
	var prettyJSON bytes.Buffer
	json.Indent(&prettyJSON, data, "", "  ")
	fmt.Println("美化后的 JSON:")
	fmt.Println(prettyJSON.String())
}
